package com.mayikt.pay.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.mayikt.core.util.GenerateTokenUtils;
import com.mayikt.pay.mapper.entity.PaymentTransaction;
import com.mayikt.weixin.input.dto.PayCratePayTokenDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.pay.mapper.PaymentTransactionMapper;
import com.mayikt.pay.service.PayMentTransacTokenService;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@RestController
@Service
public class PayMentTransacTokenServiceImpl extends BaseApiService<JSONObject> implements PayMentTransacTokenService {
	@Autowired
	private PaymentTransactionMapper paymentTransactionMapper;

	@Autowired
	private GenerateTokenUtils generateToken;

	@Override
    @Transactional(rollbackFor = Exception.class)
	public BaseResponse<JSONObject> cratePayToken(@RequestBody PayCratePayTokenDTO payCratePayTokenDTO) {
		String orderId = payCratePayTokenDTO.getOrderId();
		if (StringUtils.isEmpty(orderId)) {
			return setResultError("订单号码不能为空!");
		}
        BigDecimal payAmount = payCratePayTokenDTO.getPayAmount();
        if (payAmount == null) {
			return setResultError("金额不能为空!");
		}
		Long userId = payCratePayTokenDTO.getUserId();
		if (userId == null) {
			return setResultError("userId不能为空!");
		}
		// 2.将输入插入数据库中 待支付记录
		PaymentTransaction paymentTransaction = new PaymentTransaction();
        paymentTransaction.setOrderId(orderId);
        paymentTransaction.setPayAmount(payAmount);
        paymentTransaction.setUserId(userId);
        paymentTransaction.setCreateTime(LocalDateTime.now());
        paymentTransaction.setUpdateTime(paymentTransaction.getCreateTime());
		// 使用雪花算法 生成全局id
        Snowflake snowflake = new Snowflake(1,1);
        paymentTransaction.setPaymentId(""+snowflake.nextId());
		int row = paymentTransactionMapper.insert(paymentTransaction);
		if (row <= 0) {
			return setResultError("系统错误!");
		}
		// 获取主键id
		Long payId = paymentTransaction.getId();
		if (payId == null) {
			return setResultError("系统错误!");
		}

		// 3.生成对应支付令牌
		String keyPrefix = "pay_";
		String token = generateToken.createToken(keyPrefix, payId + "",3600*2L);
		JSONObject data = new JSONObject();
        data.put("token", token);

		return setResultSuccess(data);
	}

}
